package org.dreamwork.tools.network.bridge.client.fx;

import javafx.application.Platform;
import javafx.stage.Stage;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * Created by seth.yang on 2020/3/9
 */
public class SystemNotification {
    private static TrayIcon tray;
    private static ResourceBundle bundle;

    static {
        bundle = ResourceBundle.getBundle ("value.strings");
        GuiContext.ui = bundle;
    }

    public static void notify (String message) {
        if (tray != null) {
            tray.displayMessage (null, message, TrayIcon.MessageType.NONE);
        }
    }

    public static void error (String message) {
        if (tray != null) {
            tray.displayMessage (null, message, TrayIcon.MessageType.ERROR);
        }
    }

    public static void success (String message) {
        if (tray != null) {
            tray.displayMessage (null, message, TrayIcon.MessageType.INFO);
        }
    }

    public static void warn (String message) {
        if (tray != null) {
            tray.displayMessage ("WARN", message, TrayIcon.MessageType.WARNING);
        }
    }

    public static void setup () {
        if (SystemTray.isSupported ()) {
            ClassLoader loader = GuiTools.class.getClassLoader ();
            URL url = loader.getResource ("images/16x16/route.png");
            if (url != null) {
                ActionListener main = e -> {
                    Stage state = GuiContext.getMainStage ();
                    Platform.runLater (()->{
                        state.show ();
                        state.toFront ();
                    });
                };

                ImageIcon icon = new ImageIcon (url);
                PopupMenu popup = new PopupMenu ();

                MenuItem item = new MenuItem (bundle.getString ("tray.mi.restore"));
                item.addActionListener (main);
                popup.add (item);

                popup.addSeparator ();

                item = new MenuItem (GuiContext.ui.getString ("global.label.exit"));
                item.addActionListener (e->{
                    Stage stage = GuiContext.getMainStage ();
                    if (stage != null) {
                        Platform.runLater (stage::close);
                    }

                    System.exit (0);
                });
                popup.add (item);

                tray = new TrayIcon (icon.getImage (), GuiContext.ui.getString ("main.title"), popup);
                tray.addActionListener (main);
                try {
                    SystemTray.getSystemTray ().add (tray);
                } catch (AWTException ex) {
                    ex.printStackTrace ();
                }
            }
        }
    }

    public static void main (String[] args) {
        SystemNotification.setup ();
    }
}
